<script setup>

import {Delete, Edit, Search, Setting} from "@element-plus/icons-vue";
import {onMounted, ref, reactive} from "vue";
import axios from "axios";

// 查询条件
let queryInfo = reactive({
  query: '',
  pagenum: 1,
  pagesize: 2,
})
// 添加用户弹窗
let addDialogVisible = ref(false)
// 用户列表
let userList = ref([])
let editDialogVisible = ref(false)
//  查询的总条数
let totals = ref(0)

let setRoleDialogVisible = ref(false)
let userInfo = ref({})
let roleList = ref([])
let selectedRoleId = ref('')
// 表单对象引用
const addUserFormRef = ref()
// 定义表单数据对象，用于提交表单
const addUserForm = reactive({
  username: '',
  password: '',
  email: '',
  mobile: ''
})
const editUserFormRef = ref()
const editUserForm = reactive({
  email: '',
  mobile: ''
})
// 检查邮箱是否合法 rule ：验证规则， value：表单的值，callback：回调函数
const checkEmail = (rule, value, callback) => {
  const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
  if (reg.test(value)) {
    callback();
  } else {
    callback(new Error('请输入正确的邮箱格式'));
  }
}
// 验证手机号是否合法 rule ：验证规则， value：表单的值，callback：回调函数
const checkMobile = (rule, value, callback) => {
  const reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
  if (reg.test(value)) {
    callback();
  } else {
    callback(new Error('请输入正确的手机号格式'));
  }
}
const addUserFormRules = {
  username: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
    {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'}
  ],
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {validator: checkEmail, trigger: 'blur'}
  ],
  mobile: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {validator: checkMobile, trigger: 'blur'}
  ]
}


const editUserFormRules = {
  email: [
    {required: true, message: '请输入邮箱', trigger: 'blur'},
    {validator: checkEmail, trigger: 'blur'}
  ],
  mobile: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {validator: checkMobile, trigger: 'blur'}
  ]
}

const getUserList = async () => {
  const {data: res} = await axios.get('users', {params: queryInfo})
  // console.log(res)
  if (res.meta.status !== 200) {
    ElMessage.error('获取用户列表失败')
    return
  }
  // 获取用户列表
  // Object.assign(userList, res.data.users)

  userList.value = res.data.users
  // console.log(userList)
  // 获取总条数
  totals.value = res.data.total
}


//添加用户对话框关闭事件
const addDialogClosed = () => {
  addUserFormRef.value.resetFields()
}
//修改用户对话框关闭事件
const editDialogClosed = () => {
  editUserFormRef.value.resetFields()
}

// 改变当前页
function handleCurrentChange(newPage) {
  queryInfo.pagenum = newPage
  console.log(queryInfo.pagenum); // 打印新的页码
  getUserList()
}

// 改变每页条数
function handleSizeChange(newSize) {
  // console.log('New size:', newSize); // 打印新的页面大小
  queryInfo.pagesize = newSize;
  console.log('New page:', queryInfo.pagesize); // 打印新的页码
  console.log('New num:', queryInfo.pagenum); // 打印新的页码
  console.log(userList); // 打印用户列表
  getUserList(); // 等待获取用户列表完成
}

// 监听switch组件用户状态改变
const userStateChanged = async (userInfo) => {
  const {data: res} = await axios.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
  if (res.meta.status !== 200) {
    ElMessage.error('用户状态修改失败')
    userInfo.mg_state = !userInfo.mg_state // 还原状态
    return
  }
  ElMessage.success('用户状态修改成功')
}
// 添加用户，发起axios请求
const addUser = () => {
  // 校验表单
  addUserFormRef.value.validate(async (valid) => {
    if (!valid) return
    // 发起axios请求
    const {data: res} = await axios.post('users', addUserForm)
    if (res.meta.status !== 201)
      ElMessage.error('添加用户失败')
    else {
      ElMessage.success('添加用户成功')
      // 关闭添加对话框
      addDialogVisible.value = false
      // 刷新用户列表
      await getUserList()
    }
  })
}
// 修改用户，发起axios请求
const editUser = () => {
  // 校验表单
  editUserFormRef.value.validate(async (valid) => {
    if (!valid) return
    // 发起axios请求,返回promised对象
    const {data: res} = await axios.put(`users/${editUserForm.id}`,
        {email: editUserForm.email, mobile: editUserForm.mobile})
    if (res.meta.status !== 200)
      ElMessage.error('更新用户信息失败')
    else {
      await getUserList()
      ElMessage.success('修改用户成功')
    }
    editDialogVisible.value = false
  })
}

const saveRoleInfo = async () => {
  if(!selectedRoleId.value) {
    ElMessage.error('请选择角色')
    return
  }
  const {data: res} = await axios.put(`users/${userInfo.value.id}/role`,{rid:selectedRoleId.value})
  if (res.meta.status !== 200) {
    ElMessage.error('设置用户角色失败')
    return
  }

  ElMessage.success('设置用户角色成功')
  await getUserList()
  setRoleDialogVisible.value = false
}
// 展示编辑用户对话框
const showShowDialog = async (id) => {
  const {data: res} = await axios.get(`users/${id}`)
  if (res.meta.status !== 200) {
    ELMessage.error('获取用户信息失败')
  } else {
    Object.assign(editUserForm, res.data)
    editDialogVisible.value = true
  }
}

// 删除用户
const removeById = async (id) => {
  // 如果用户确认删除，则返回值为字符串 confirm
  // 如果用户取消了删除，则返回值为字符串 cancel
  const confirmResult = await ElMessageBox.confirm(
      '次操作将永久删除改用户，是否继续?',
      '提示',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
  ).catch(error => error)
  console.log(confirmResult)
  // 点击取消按钮
  if (confirmResult !== 'confirm') {
    ElMessage.info('取消删除')
    return
  }
  const {data: res} = await axios.delete(`users/${id}`)
  if (res.meta.status !== 200) {
    ElMessage.error('删除用户失败')
  } else {
    ElMessage.success('删除用户成功')
    await getUserList()
  }
}

const setRole = async (userinfo) => {
  const {data: res} = await axios.get('roles')
  if (res.meta.status !== 200) {
    ElMessage.error("请求角色列表失败")
    return
  }
  // roleList = res.data
  // Object.assign(roleList, res.data)
  roleList.value = res.data
  userInfo.value = userinfo
  setRoleDialogVisible.value = true
}
onMounted(() => {
  getUserList()
})
</script>

<template>
  <div>
    <!-- 面包蟹导航区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="Please input"
                    clearable
                    v-model="queryInfo.query"
                    @clear="getUserList()">
            <template #append>
              <el-button :icon="Search" @click="getUserList()"/>
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="userList" :border="true" :stripe="true">
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态" width="130"> <!-- 无需指定prop -->
          <!--作用域插槽的使用-->
          <template #default="scope">
            <el-switch @change="userStateChanged(scope.row)" v-model="scope.row.mg_state"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" :icon="Edit" size="small" @click="showShowDialog(scope.row.id)"/>
            <!-- 删除按钮 -->
            <el-button type="danger" :icon="Delete" size="small" @click="removeById(scope.row.id)"/>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" :icon="Setting" size="small" @click="setRole(scope.row)"/>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
          :current-page.sync="queryInfo.pagenum"
          :page-size.sync="queryInfo.pagesize"
          :page-sizes="[1,2,5,10]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totals"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>
    <!-- 弹窗区域对话框 添加用户 -->
    <el-dialog
        title="添加用户"
        width="50%"
        v-model="addDialogVisible"
        @close="addDialogClosed">
      <!-- 添加用户表单主体内容区域 -->
      <span>
        <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username" type="text" placeholder="用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password" type="password" placeholder="密码"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
             <el-input v-model="addUserForm.email" type="text" placeholder="邮箱"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile" type="text" placeholder="电话">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <!-- 弹窗底部区域 -->
      <template #footer>
        <el-button @click="addDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="addUser()">
          Confirm
        </el-button>
      </template>
    </el-dialog>    <el-dialog
        title="添加用户"
        width="50%"
        v-model="addDialogVisible"
        @close="addDialogClosed">
      <!-- 添加用户表单主体内容区域 -->
      <span>
        <el-form :model="addUserForm" :rules="addUserFormRules" ref="addUserFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username" type="text" placeholder="用户名"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password" type="password" placeholder="密码"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
             <el-input v-model="addUserForm.email" type="text" placeholder="邮箱"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile" type="text" placeholder="电话">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <!-- 弹窗底部区域 -->
      <template #footer>
        <el-button @click="addDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="addUser()">
          Confirm
        </el-button>
      </template>
    </el-dialog>


    <!-- 弹窗区域对话框 修改用户 -->
    <el-dialog
        title="修改用户"
        width="50%"
        v-model="editDialogVisible"
        @close="editDialogClosed">
      <!-- 修改用户表单主体内容区域 -->
      <span>
        <el-form :model="editUserForm" :rules="editUserFormRules" ref="editUserFormRef" label-width="70px">
          <el-form-item label="用户名">
             <el-input v-model="editUserForm.username" type="text" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
             <el-input v-model="editUserForm.email" type="text" placeholder="邮箱"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile" type="text" placeholder="电话">
            <el-input v-model="editUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <!-- 弹窗底部区域 -->
      <template #footer>
        <el-button @click="editDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="editUser()">
          Confirm
        </el-button>
      </template>
    </el-dialog>


    <!-- 弹窗区域对话框 为用户分配角色 -->
    <el-dialog
        title="分配角色"
        width="50%"
        v-model="setRoleDialogVisible"
    >
      <!-- 修改用户表单主体内容区域 -->
      <span>
      <div>
        <p>当前的用户：{{ userInfo.username }}</p>
        <p>当前的角色 ：{{ userInfo.role_name }}</p>
        <p>分配新角色：
           <el-select
               v-model="selectedRoleId"
               class="m-2"
               placeholder="Select"
               size="small"
               style="width: 240px"
           >
            <el-option
                v-for="role in roleList"
                :key="role.id"
                :label="role.roleName"
                :value="role.id"
            />
          </el-select>
        </p>
      </div>
      </span>
      <!-- 弹窗底部区域 -->
      <template #footer>
        <el-button @click="setRoleDialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="saveRoleInfo()">
          Confirm
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">

</style>
